package com.mantru.iotpot;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Debug;
import android.os.StatFs;

import java.io.BufferedReader;
import java.io.FileReader;

public class SystemResourceMonitor {
    private Context context;

    public SystemResourceMonitor(Context context) {
        this.context = context;
    }

    // 计算 CPU 使用率（此方法返回 整体 CPU 使用率）
    public double calculateCpuUsage() {//CPU使用率 = (总时间差 - 空闲时间差) / 总时间差 * 100%
        // 读取 /proc/stat 两次，间隔 200ms， 计算两次 CPU 时间差，推导使用率
        try {
            BufferedReader br = new BufferedReader(new FileReader("/proc/stat"));
            String line;
            long[] preCpuTimes = new long[4];
            long[] curCpuTimes = new long[4];
            while ((line = br.readLine()) != null) {
                if (line.startsWith("cpu ")) {
                    String[] parts = line.split("\\s+");
                    preCpuTimes[0] = Long.parseLong(parts[1]); // user
                    preCpuTimes[1] = Long.parseLong(parts[2]); // nice
                    preCpuTimes[2] = Long.parseLong(parts[3]); // system
                    preCpuTimes[3] = Long.parseLong(parts[4]); // idle
                    break;
                }
            }
            br.close();
            Thread.sleep(200);
            br = new BufferedReader(new FileReader("/proc/stat"));
            while ((line = br.readLine()) != null) {
                if (line.startsWith("cpu ")) {
                    String[] parts = line.split("\\s+");
                    curCpuTimes[0] = Long.parseLong(parts[1]);
                    curCpuTimes[1] = Long.parseLong(parts[2]);
                    curCpuTimes[2] = Long.parseLong(parts[3]);
                    curCpuTimes[3] = Long.parseLong(parts[4]);
                    break;
                }
            }
            br.close();
            long preTotalCpu = preCpuTimes[0] + preCpuTimes[1] + preCpuTimes[2];
            long preIdleCpu = preCpuTimes[3];
            long curTotalCpu = curCpuTimes[0] + curCpuTimes[1] + curCpuTimes[2];
            long curIdleCpu = curCpuTimes[3];
            long totalInterval = curTotalCpu - preTotalCpu;
            long idleInterval = curIdleCpu - preIdleCpu;
            return (totalInterval - idleInterval) * 100.0 / totalInterval;
        } catch (Exception e) {
            e.printStackTrace();
            return 0.0;
        }
    }

    // 获取 RAM 信息（总内存 GB，可用内存 MB）
    public String getRamInfo() {
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(memoryInfo);
        double totalMemGb = memoryInfo.totalMem / (1024.0 * 1024.0 * 1024.0); // 设备总物理内存（单位：字节）,转换为 GB
        double availMemMb = memoryInfo.availMem / (1024.0 * 1024.0); // 当前可用内存（单位：字节）,转换为 MB
        return String.format("总内存: %.2f GB，可用内存: %.2f MB", totalMemGb, availMemMb);
    }

    // 获取存储信息（总存储 GB，可用存储 MB）
    public String getStorageInfo() {
        StatFs statFs = new StatFs(context.getExternalFilesDir(null).getPath());
        long blockSize = statFs.getBlockSizeLong();//文件系统块大小（单位：字节）
        long totalBlocks = statFs.getBlockCountLong();//总块数
        long availableBlocks = statFs.getAvailableBlocksLong();//可用块数。
        double totalStorageGb = (totalBlocks * blockSize) / (1024.0 * 1024.0 * 1024.0); // 转换为 GB
        double availableStorageMb = (availableBlocks * blockSize) / (1024.0 * 1024.0); // 转换为 MB
        return String.format("总存储: %.2f GB，可用存储: %.2f MB", totalStorageGb, availableStorageMb);
    }

    public String getAppMemoryUsage() {
        Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();
        Debug.getMemoryInfo(memoryInfo);
        double appMemUsageMb = memoryInfo.getTotalPrivateDirty() / 1024.0; // 直接转换为 MB
        return String.format("应用内存占用: %.2f MB", appMemUsageMb);
    }
}
